package jude.java.money.article;

import java.io.File;

import jude.java.money.task.SimpleTask;
import jude.java.util.WebUtils;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang.StringUtils;

public abstract class GatherTask extends SimpleTask<String> {
	
	protected static final String SAVE_PATH = "E:\\articles\\";
	private static final String ENCODING = "ISO-8859-1";
	protected static final char[] NEW_LINE = {'\r', '\n'};
	
	protected HttpClient client;
	protected boolean denied;
	
	private String referer;
	private String cookie = "sessionID=1283002190867546000";
	
	public GatherTask(String... urls) {
		super(urls);
	}

	@Override
	protected void execute(String url) {
		if (isDenied())
			return;
		client = getHttpClient();
		System.out.println(url);
		GetMethod get = getMethod(url);
		try {
			int statusCode = client.executeMethod(get);
			if (statusCode != HttpStatus.SC_OK) {
				return;
			}
			referer = url;
			String response = WebUtils.getResponse(get, 81920, ENCODING);
			if (response == null)
				return;
			saveCookies(get);
			gather(url, response);
			get.releaseConnection();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	protected abstract void gather(String url, String response) throws Exception;
	
	protected boolean isDenied() {
		return denied;
	}
	
	protected boolean isDenied(String response) {
		return false;
	}
	
	protected String getEncoding() {
		return ENCODING;
	}
	
	protected String getSiteIdentify() {
		return null;
	}
	
	protected String getStoragePath() {
		StringBuilder sb = new StringBuilder(SAVE_PATH);
		String site = getSiteIdentify();
		if (StringUtils.isNotEmpty(site)) {
			sb.append(site).append(File.separator);
		}
//		sb.append(DateUtils.toString(new Date(), "MM-dd")).append(File.separator);
		return sb.toString();
	}
	
	protected String formatFileName(String name) {
		return name.trim().replaceAll("[:*?<>|\"\\/']", "-");
	}

	protected HttpClient getHttpClient() {
		referer = null;
		HttpClient client = new HttpClient();
		client.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
		client.getHttpConnectionManager().getParams().setSoTimeout(60000);
		client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); 
		return client;
	}
	
	protected GetMethod getMethod(String url) {
		GetMethod get = new GetMethod(url);
		WebUtils.pretendRequestHeader(get);
		if (cookie != null)
			get.addRequestHeader("Cookie", cookie);
		if (referer != null)
			get.addRequestHeader("Referer", referer);
		get.setFollowRedirects(true);
		return get;
	}
	
	protected PostMethod postMethod(String url) {
		PostMethod post = new PostMethod(url);
		WebUtils.pretendRequestHeader(post);
		if (cookie != null)
			post.addRequestHeader("Cookie", cookie);
		if (referer != null)
			post.addRequestHeader("Referer", referer);
		return post;
	}

	
	protected void saveCookies(HttpMethodBase method) {
		String cookie = WebUtils.getCookies(method);
		if (cookie != null) {
			if (!cookie.equals(this.cookie)) {
				this.cookie = cookie;
				System.out.println("Set-Cookie:" + cookie);
			}
		}
	}
}
